//拦截请求
import LocalStorageConstant from "@/constant/LocalStorageConstant"
import {InfoUtils, ModalUtils, UniRouter, UniStorage} from "@/util/uniUtils";
import RouterPath from "@/constant/RouterPath";

//全局提示框是否弹出标志
let loginExpiredFlag = false
//拦截加上token
const TokenInterceptor = {
    //请求前
    invoke(args) {
        //拦截,在请求发送前在header添加token
        let token = UniStorage.get(LocalStorageConstant.TOKEN)
        if (token) {
            if (!args.header) {
                args.header = {}
            }
            args.header[LocalStorageConstant.TOKEN_HEADER] = token
        }
    },
    //请求成功
    success(args) {
        let {data} = args
        //可能存在结果不是对象的情况(上传文件),所以处理一下
        if (typeof data === 'string'){
            data = JSON.parse(data)
        }
        if (data.message === 'Token失效，请重新登录'){
            InfoUtils.hideLoading()
            let pages = getCurrentPages(); //获取所有页面栈实例列表
            let [prevPage]  = pages.slice(-1) //上一页页面实例
            //防止多次拦截请求时，多次跳转登录页
            if (prevPage.$page.fullPath !== RouterPath.login.login) {
                //异步询问是否跳转
                ;(async () => {
                    if (loginExpiredFlag){
                        return
                    }
                    loginExpiredFlag=true
                    let flag = await ModalUtils.showModalPromise("登录状态已失效，是否重新登录?")
                    if (flag) {
                        //清除缓存
                        UniStorage.remove(LocalStorageConstant.TOKEN)
                        UniRouter.reLaunch(RouterPath.login.login)
                    }
                    loginExpiredFlag=false
                })()
                return false
            }

        }
    },
}
const requestList = ['request', 'uploadFile']
requestList.forEach(item => uni.addInterceptor(item, TokenInterceptor))





